package classtoview.vo;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.persistence.Id;
import org.apache.commons.beanutils.*;

public class BaseVO {
    
    public String toString() {
        String str = "";
        Field[] fields = this.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            try {
                str += fields[i].getName() + " = "
                        + PropertyUtils.getProperty(this, fields[i].getName())
                        + "\n";
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return str;
    }
    
    public String getId() {
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Id.class)) {
                try {
                    return field.getName();
                } catch (IllegalArgumentException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return null;
    }
    
    public Object getIdValue() {
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Id.class)) {
                try {
                    return PropertyUtils.getProperty(this, field.getName());
                } catch (NoSuchMethodException ex) {
                    ex.printStackTrace();
                } catch (InvocationTargetException ex) {
                    ex.printStackTrace();
                } catch (IllegalAccessException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return null;
    }
    
    public void popule(Object vo) {
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            try {
                PropertyUtils.setProperty(this, field.getName(),
                        PropertyUtils.getProperty(vo, field.getName()));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
    }
    
}
